package org.c797797ty.railway.service;

import org.c797797ty.railway.manager.UserSessionManager;
import org.c797797ty.railway.model.User;
import org.c797797ty.railway.util.ConcurrentDBUtil;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
 * @author C797797ty
 * @data 2025/11/4 14:36
 */

/**
 * 高并发用户服务 - 支持多用户同时登录
 */
public class ConcurrentUserService {
    private static final ConcurrentMap<String, User> userCache = new ConcurrentHashMap<>();

    // 注册用户
    public static User register(String username, String password) throws SQLException {
        // 检查用户名是否已存在
        if (getUserByUsername(username) != null) {
            System.out.println("用户名已存在！");
            return null;
        }

        User user = new User(0, username, password);
        ConcurrentDBUtil.executeInTransaction(conn -> {
            try (PreparedStatement stmt = conn.prepareStatement(
                    "INSERT INTO users (username, password) VALUES (?, ?)",
                    Statement.RETURN_GENERATED_KEYS)) {
                stmt.setString(1, username);
                stmt.setString(2, password);
                stmt.executeUpdate();

                try (ResultSet rs = stmt.getGeneratedKeys()) {
                    if (rs.next()) {
                        user.setId(rs.getInt(1));
                    }
                }
            }
        });

        userCache.put(username, user);
        System.out.println("注册成功！");
        return user;
    }

    // 登录验证
    public static String login(String username, String password) throws SQLException {
        User user = getUserByUsername(username);
        if (user == null || !user.getPassword().equals(password)) {
            System.out.println("用户名或密码错误！");
            return null;
        }

        return UserSessionManager.createSession(user);
    }


    // 管理员登录验证
    public static String adminLogin(String username, String password) throws SQLException {
        User user = getUserByUsername(username);
        if (user == null || !user.getPassword().equals(password) || !"admin".equals(user.getRole())) {
            System.out.println("用户名或密码错误，或者您不是管理员！");
            return null;
        }

        return UserSessionManager.createSession(user);
    }



    // 从缓存或数据库获取用户
    private static User getUserByUsername(String username) throws SQLException {
        User user = userCache.get(username);
        if (user == null) {
            user = ConcurrentDBUtil.executeQuery(rs -> {
                if (rs.next()) {
                    return new User(rs.getInt("id"), username, rs.getString("password"), rs.getString("role"));
                }
                return null;
            }, "SELECT * FROM users WHERE username = ?", username);

            if (user != null) {
                userCache.put(username, user);
            }
        }
        return user;
    }
}